package com.xiaoxin.codesandbox;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import com.xiaoxin.codesandbox.modle.ExecuteCodeRequest;
import com.xiaoxin.codesandbox.modle.ExecuteCodeResponse;
import com.xiaoxin.codesandbox.modle.ExecuteMessage;
import com.xiaoxin.codesandbox.modle.JudgeInfo;
import com.xiaoxin.codesandbox.utils.ProcessUtil;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 实现代码沙箱接口
 */
public class DockerCodeSandBoxImpl extends JavaCodeSandBoxTemplate{

    public static void main(String[] args) {
        ExecuteCodeRequest executeCodeRequest = new ExecuteCodeRequest();
        executeCodeRequest.setLanguage("java");
        executeCodeRequest.setCode(ResourceUtil.readStr("testCode/Main.java", StandardCharsets.UTF_8));
        executeCodeRequest.setInputList(Arrays.asList("1 2", "3 4"));
        DockerCodeSandBoxImpl codeSandBox = new DockerCodeSandBoxImpl();
        ExecuteCodeResponse executeCodeResponse = codeSandBox.doExecute(executeCodeRequest);
        System.out.println(executeCodeResponse);
    }

    @Override
    public List<ExecuteMessage> runUserCode(List<String> inputList, File userCodeToFile) {
        /**
         * 创建容器，将编译好的代码上传到容器中
         */
        String parentCodePath = userCodeToFile.getParentFile().getAbsolutePath();
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        String image = "openjdk:8-alpine";
        //拉取镜像
        PullImageCmd pullImageCmd = dockerClient.pullImageCmd(image);
        PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
            @Override
            public void onNext(PullResponseItem item) {
                System.out.println("下载镜像：" + item.getStatus());
                super.onNext(item);
            }
        };
        try {
            pullImageCmd.exec(pullImageResultCallback).awaitCompletion();
        } catch (InterruptedException e) {
            System.out.println("拉取镜像失败");
            throw new RuntimeException(e);
        }
        System.out.println("镜像下载完成");
        //创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(image);
        HostConfig hostConfig = new HostConfig();
        hostConfig.withMemory(100 * 1000 * 1000L);
        hostConfig.withCpuCount(1L);
        //将编译好的代码文件上传到容器中
        hostConfig.setBinds(new Bind(parentCodePath, new Volume("/app")));
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)
                .withReadonlyRootfs(true)
                .withAttachStderr(true)
                .withAttachStdin(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        System.out.println(createContainerResponse);
        String containerResponseId = createContainerResponse.getId();
        //启动容器
        StartContainerCmd startContainerCmd = dockerClient.startContainerCmd(containerResponseId);
        startContainerCmd.exec();
        /**
         * 运行用户的class代码
         */
        // docker exec keen_chaplygin java -cp /app Main 1 3
        List<ExecuteMessage> executeMessageList=new ArrayList<>();
        for(String input:inputList) {
            ExecuteMessage executeMessage = new ExecuteMessage();
            StopWatch stopWatch=new StopWatch();
            String[] arrString = input.split(" ");
            String[] arrCmd = ArrayUtil.append(new String[]{"java", "-cp", "/app", "Main"}, arrString);
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerResponseId)
                    .withCmd(arrCmd)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();
            String id = execCreateCmdResponse.getId();
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        System.out.println("错误信息：" + new String(frame.getPayload()));
                        executeMessage.setErrorMessage(new String(frame.getPayload()));
                    } else {
                        System.out.println("结果："+new String(frame.getPayload()));
                        executeMessage.setMessage(new String(frame.getPayload()));
                    }
                    super.onNext(frame);
                }
            };
            //获取内存
            final long[] maxMemory = {0L};
            StatsCmd statsCmd = dockerClient.statsCmd(containerResponseId);
            ResultCallback<Statistics> resultCallback=new ResultCallback<Statistics>() {
                @Override
                public void onStart(Closeable closeable) {

                }

                @Override
                public void onNext(Statistics statistics) {
                    MemoryStatsConfig memoryStats = statistics.getMemoryStats();
                    maxMemory[0] =Math.max(maxMemory[0],memoryStats.getUsage());
                    System.out.println("内存："+maxMemory[0]);
                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {

                }

                @Override
                public void close() throws IOException {

                }
            };
            statsCmd.exec(resultCallback);
            try {
                stopWatch.start();
                dockerClient.execStartCmd(id)
                        .exec(execStartResultCallback)
                        .awaitCompletion(2000L, TimeUnit.MILLISECONDS);
                stopWatch.stop();
                executeMessage.setCostTime(stopWatch.getLastTaskTimeMillis());
            } catch (InterruptedException e) {
                System.out.println("程序执行异常");
                throw new RuntimeException(e);
            }
            executeMessage.setCostMemory(maxMemory[0]);
            executeMessageList.add(executeMessage);
        }
        return executeMessageList;
    }
}

